package it.blueocean.acanto.taglibrary.jsp.taglib.tags.hibernate;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil
{
	public static final String DEFAULT_DATASOURCE = "default.hibernate";

	private Map<String, SessionFactory> factories = Collections.synchronizedMap(new HashMap());

	private static HibernateUtil instance;

	private static boolean initialized = false;

	public static HibernateUtil getInstance()
	{
		if(instance == null)
			instance = new HibernateUtil();
		return instance;
	}

	public void init()
	{
		SessionFactory localSessionFactory = null;
		AnnotationConfiguration localAnnotationConfiguration = new AnnotationConfiguration();
		localSessionFactory = localAnnotationConfiguration.configure().buildSessionFactory();
		this.factories.put("default.hibernate", localSessionFactory);
		initialized = true;
	}

	public void init(String[] paramArrayOfString) throws Exception
	{
		SessionFactory localSessionFactory = null;
		AnnotationConfiguration localAnnotationConfiguration = null;
		for (String str : paramArrayOfString)
			try
			{
				if(str.indexOf("hibernate.cfg.xml") >= 0)
				{
					init();
				}
				else
				{
					localAnnotationConfiguration = new AnnotationConfiguration();
					localSessionFactory = localAnnotationConfiguration.configure(str).buildSessionFactory();
					this.factories.put(str, localSessionFactory);
				}
			}
			catch (Exception localException)
			{
				throw new Exception("Error testing session factory [" + str + "]", localException);
			}
		initialized = true;
	}

	public SessionFactory getSessionFactory() throws Exception
	{
		return getSessionFactory("default.hibernate");
	}

	public SessionFactory getSessionFactory(String paramString) throws Exception
	{
		if(!(initialized))
			throw new Exception(
					"HibernateUtil not initialized, call init() o init(String[] configurationFileNames)before invoking HibernateUtil.getInstance()");
		if(paramString.indexOf("hibernate.cfg.xml") >= 0)
			return ((SessionFactory) this.factories.get("default.hibernate"));
		return ((SessionFactory) this.factories.get(paramString));
	}

	public void testHibernateSessionFactory(String paramString) throws Exception
	{
		SessionFactory localSessionFactory = (SessionFactory) this.factories.get(paramString);
		org.hibernate.classic.Session localSession = localSessionFactory.openSession();
		localSession.close();
		System.out.println("Tested Hibernate Session Factory [" + paramString + "].");
	}
}
